package assfur.eran.utils;

import assfur.eran.config.ConfigManger;

import java.io.*;
import java.nio.channels.FileChannel;

public class FileUtils {

    public static void writeStringToFile(String _str, String _filePath) {
        try {
            File f = new File(_filePath);
            if (f.exists()) {
                f.delete();
            }
            f.createNewFile();
            OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(f, true), "UTF-8");
            ow.write(_str);
            ow.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将文件内的所有内容读到一个String中,常用于JSON解析
     */
    public static String readStringFromFile(String _filePath) {
        String str = "";
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(new File(_filePath)));
            String tempString;
            while ((tempString = reader.readLine()) != null) {
                str += tempString;
            }
            reader.close();
        } catch (IOException e) {
            return null;
        }
        return str;
    }

    /**
     * 取得文件相对于InputPath的相对路径
     * <p>
     * 比如一个文件在本地磁盘的绝对路径是
     * D:\TestZone\Input\F_A\B.txt
     * Input路径为
     * D:\TestZone\Input
     * 则该文件的相对路径为
     * F_A\B.txt
     */
    public static String getFileRelatePath(File _file) {
        String filePath = _file.getPath();
        return filePath.replace(ConfigManger.getInstance().getMeta().inputPath, "");
    }

    public static void copyFile(File input, File output) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        FileChannel inputFileChannel = null;
        FileChannel outputFileChannel = null;
        try {
            inputStream = new FileInputStream(input);
            outputStream = new FileOutputStream(output);
            inputFileChannel = inputStream.getChannel();
            outputFileChannel = outputStream.getChannel();
            inputFileChannel.transferTo(0, inputFileChannel.size(), outputFileChannel);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputFileChannel != null) {
                    inputFileChannel.close();
                }
                if (outputFileChannel != null) {
                    outputFileChannel.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
